package com.qcb.expresswrapping.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qcb.expresswrapping.common.Result;
import com.qcb.expresswrapping.entity.LogisticsInfo;
import com.qcb.expresswrapping.entity.SendOrder;
import com.qcb.expresswrapping.entity.StationExpress;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: QCB
 * @create: 2022-03-11-17:38
 * To change this template use File | Settings | File and Code Templates.
 */
@RestController
@RequestMapping("/sc/order")
public class ScSendOrderController extends BaseController{

    @GetMapping("/list")
    @PreAuthorize("hasAnyAuthority('sc:order:list')")
    public Result list(String orderId, String posName, Principal principal){

        Page<SendOrder> pageData = scSendOrderService.page(getPage(), new QueryWrapper<SendOrder>()
                .eq("stationId", sysUserService.getByUsername(principal.getName()).getId())
                .like(StrUtil.isNotBlank(orderId), "orderId", orderId)
                .like(StrUtil.isNotBlank(posName), "posName", posName)
                .eq("status", 0)
        );

        return Result.success(pageData);
    }

    @GetMapping("/info/{orderId}")
    @PreAuthorize("hasAnyAuthority('sc:order:info')")
    public Result info(@PathVariable("orderId") String orderId){
        SendOrder sendOrder = scSendOrderService.getById(orderId);
        Assert.notNull(sendOrder, "查询不到该订单信息");
        List<LogisticsInfo> logisticsInfos = logisticsInfoService.listLogisiticsByOrderId(orderId);
        logisticsInfos.forEach(l ->{
            l.setCourier(pcUserInfoService.getById(l.getCourierId()));
        });
        sendOrder.setLogisticsInfos(logisticsInfos);
        return Result.success(sendOrder);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAnyAuthority('sc:order:save')")
    public Result save(@Validated @RequestBody SendOrder sendOrder, Principal principal){
        String orderNum = "MTS" + new SimpleDateFormat("yyMMdd").format(new Date()) + (int)((Math.random()*9+1)*10000);
        sendOrder.setOrderId(orderNum);
        sendOrder.setStationId(sysUserService.getByUsername(principal.getName()).getId());
        sendOrder.setCreateDate(new Date());
        sendOrder.setUpdateDate(new Date());
        sendOrder.setStatus(0);
        scSendOrderService.save(sendOrder);
        return Result.success(sendOrder);
    }

    @GetMapping("/delete/{orderId}")
    @PreAuthorize("hasAnyAuthority('sc:order:delete')")
    public Result delete(@PathVariable("orderId") String orderId){
        scSendOrderService.removeById(orderId);
        return Result.success("删除成功！");
    }

    @PostMapping("/update")
    @PreAuthorize("hasAnyAuthority('sc:order:update')")
    public Result update(@Validated @RequestBody SendOrder sendOrder){
        sendOrder.setUpdateDate(new Date());
        scSendOrderService.updateById(sendOrder);
        return Result.success(sendOrder);
    }

    @Transactional
    @PostMapping("/checkAndSave")
    @PreAuthorize("hasAnyAuthority('sc:order:check')")
    public Result checkAndSave(@Validated @RequestBody SendOrder sendOrder, Principal principal){
        sendOrder.setUpdateDate(new Date());
        sendOrder.setStatus(1);
        scSendOrderService.updateById(sendOrder);
        StationExpress stationExpress = new StationExpress();
        stationExpress.setOrderId(sendOrder.getOrderId());
        stationExpress.setEnterDate(new Date());
        stationExpress.setStationId(sysUserService.getByUsername(principal.getName()).getId());
        stationExpress.setStatus(0);
        scStationExpressService.save(stationExpress);
        return Result.success(stationExpress);
    }

    @PostMapping("/checkAndRefuse")
    @PreAuthorize("hasAnyAuthority('sc:order:refuse')")
    public Result checkAndRefuse(@Validated @RequestBody SendOrder sendOrder, Principal principal){
        sendOrder.setUpdateDate(new Date());
        sendOrder.setStatus(5);
        scSendOrderService.updateById(sendOrder);
        return Result.success(sendOrder);
    }

}
